package com.yeyv.net.UsefulEntity;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 常量
 *
 * @type Entity
 * @author 夜雨
 * @do 常量定义
 */
public class Constant {
    //#region 默认返回值
    /**
     * 默认成功返回
     * <p>当修改code与msg同时修改Resp返回</p>
     */
    public static Resp ResponseSuccess(){
        return new Resp<>(200, "请求成功", "Success", null);
    }

    /**
     * 默认失败返回
     * <p>当修改code与msg同时修改Resp返回</p>
     */
    public static Resp ResponseError() {
        return new Resp<>(400,"请求失败","Error",null);
    }

    /**
     * 默认验证失败返回
     * <p>当修改code与msg同时修改Resp返回</p>
     */
    public static Resp ResponseAuthReject() {
        return new Resp<>(401,"验证出错","Auth Error",null);
    }
    //#endregion

    //#region 获取IP地址
    public static String getIp() {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            return "unknown";
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    //#endregion

    public static String random(int size) {
        String[] letters = {
                "A", "B", "C",
                "D", "E", "F",
                "G", "H", "I",
                "J", "K", "L",
                "M", "N", "O",
                "P", "Q", "R",
                "S", "T", "U",
                "V", "W", "X",
                "Y", "Z", "0",
                "1", "2", "3",
                "4", "5", "6",
                "7", "8", "9",
        };
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < size; i++) {
            result.append(letters[(int) (Math.random() * letters.length)]);
        }
        return result.toString();
    }
}
